#include <iostream>
#include <fstream>

#include "contacts.pb.h"

#define CONTACTS_FILE "./contacts.bin"

void printfContact(const contacts2::Contacts &contact)
{
    for(int i = 0; i < contact.peoples_size(); ++i)
    {
        std::cout << "----------联系人" << i + 1 << "----------" << std::endl;
        contacts2::PeopleInfo people = contact.peoples(i);
        std::cout << "姓名: " << people.name() << std::endl;
        std::cout << "年龄: " << people.age() << std::endl;
        //电话
        for(int j = 0; j < people.phone_size(); ++j)
        {
            const contacts2::PeopleInfo_Phone &phone = people.phone(j);
            std::cout << j + 1 << "电话: " << phone.phone()
                      << "  (" << phone.PhoneType_Name(phone.type()) << ")" << std::endl;
        }
        //地址
        if(people.has_data() && people.data().Is<contacts2::Address>())
        {
            contacts2::Address address;
            people.data().UnpackTo(&address);
            if(!address.host_address().empty())
                std::cout << "家庭地址: " << address.host_address() << std::endl;
            if(!address.unit_address().empty())
                std::cout << "单位地址: " << address.unit_address() << std::endl; 
        }
        // 其他联系方式
        // if(people.has_qq())
        //     std::cout << "qq号: " << people.qq() << std::endl;
        // else if(people.has_wechat())
        //     std::cout << "微信号: " << people.wechat() << std::endl;
        switch (people.other_contact_case())
        {
        case contacts2::PeopleInfo::OtherContactCase::kQq:
            std::cout << "QQ号: " << people.qq() << std::endl;
            break;
        case contacts2::PeopleInfo::OtherContactCase::kWechat:
            std::cout << "微信号: " << people.wechat() << std::endl;
            break;
        default:
            break;
        }

        //备注信息
        for(auto it = people.remark().cbegin(); it != people.remark().cend(); ++it)
            std::cout << "备注信息标题: " << it->first << std::endl << "备注信息内容: " << it->second << std::endl;
    }
}

int main()
{
    //读取通讯录文件，并反序列化
    contacts2::Contacts contact;
    std::ifstream input(CONTACTS_FILE, std::ios::in | std::ios::binary);
    if(!contact.ParseFromIstream(&input))
    {
        std::cerr << "反序列化通讯录文件失败" << std::endl;
        input.close();
        return -1;
    }
    //打印联系人信息
    printfContact(contact);
}